package upload

import (
	"errors"
	"fmt"
	"github.com/flaravel/quanlaolao/pkg/config"
	"github.com/flaravel/quanlaolao/pkg/file"
	"github.com/flaravel/quanlaolao/pkg/logger"
	"github.com/flaravel/quanlaolao/pkg/types"
	"io"
	"log"
	"mime/multipart"
	"os"
	"path"
	"strings"
)

// 获取图片完整访问 URL
func GetImageFullUrl(name string) string {
	return config.GetString("app.url") + "/" + GetImagePath() + name
}

// 获取图片上传路径
func GetImagePath() string {
	return config.GetString("storage.save_path")
}

// 上传路径
func GetImageFullPath(path string) string {
	return "public/" + GetImagePath() + path + "/"
}

// 获取图片名称
func GetImageName(name string) string {
	ext := path.Ext(name)
	fileName := strings.TrimSuffix(name, ext)
	fileName = types.EncodeMD5(fileName)
	return fileName + ext
}

// 检查图片后缀
func CheckImageExt(fileName string) bool {
	ext := file.GetExt(fileName)
	for _, allowExt := range strings.Split(config.GetString("storage.allow_exts"),",") {
		if strings.ToUpper(allowExt) == strings.ToUpper(ext) {
			return true
		}
	}
	return false
}

// 检查图片大小
func CheckImageSize(f multipart.File) bool {
	size, err := file.GetSize(f)
	if err != nil {
		log.Println(err)
		return false
	}
	return size <= config.GetInt("storage.max_size") << 10 << 10
}

// 检查图片
func CheckImage(src string) error {
	dir, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("os.Getwd err: %v", err)
	}

	err = file.IsNotExistMkDir(dir + "/" + src)
	if err != nil {
		return fmt.Errorf("file.IsNotExistMkDir err: %v", err)
	}

	perm := file.CheckPermission(src)
	if perm == true {
		return fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
	}

	return nil
}

// 图片上传
func UploadImage(file multipart.File,image *multipart.FileHeader,path string) (url string , err error) {

	imageName := GetImageName(image.Filename)
	fullPath := GetImageFullPath(path)

	pathName :=  path + "/" + imageName
	src := fullPath + imageName

	if !CheckImageExt(imageName) {
		return "", errors.New("文件格式错误")
	}
	if !CheckImageSize(file) {
		return "", errors.New(fmt.Sprintf("文件最大不超过%dm",config.GetInt("storage.max_size")))
	} else {
		err := CheckImage(fullPath)
		if err != nil {
			return "", errors.New("检查图片失败")
		} else if err := SaveUploadedFile(image, src); err != nil {
			logger.LogError(err)
			return "", errors.New("检查图片失败")
		} else {
			return GetImageFullUrl(pathName), nil
		}
	}
}

// SaveUploadedFile uploads the form file to specific dst.
func SaveUploadedFile(file *multipart.FileHeader, dst string) error {
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, src)
	return err
}